package com.sicent.app0013.operate.data;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sicent.app0013.operate.model.AppBarDetail;
import com.sicent.app0013.operate.model.AppVersion;
import com.sicent.app0013.operate.model.BarInfo;
import com.sicent.app0013.operate.model.InternetBar;
import com.sicent.app0013.operate.model.InternetBarExtend;
import com.sicent.app0013.operate.model.Prize;
import com.sicent.app0013.operate.model.PrizeRecord;
import com.sicent.app0013.operate.model.PushMsg;
import com.sicent.app0013.operate.model.Region;
import com.sicent.app0013.operate.model.WelfareActivities;
import com.sicent.app0013.operate.service.AppVersionService;
import com.sicent.app0013.operate.service.BarCommentService;
import com.sicent.app0013.operate.service.BarInfoService;
import com.sicent.app0013.operate.service.FavoriteInternetBarService;
import com.sicent.app0013.operate.service.InternetBarExtendService;
import com.sicent.app0013.operate.service.InternetBarService;
import com.sicent.app0013.operate.service.PrizeRecordService;
import com.sicent.app0013.operate.service.PrizeService;
import com.sicent.app0013.operate.service.PushMsgService;
import com.sicent.app0013.operate.service.RegionService;
import com.sicent.app0013.operate.service.WelfareActivitiesService;
import com.sicent.operate.common.base.dao.PageInfo;
import com.sicent.operate.common.util.FormatUtils;
import com.sicent.operate.common.util.HttpClientUtil;
import com.sicent.operate.common.util.UploadUtil;

@Component
public class AppData {
	Logger logger = LoggerFactory.getLogger(AppData.class);
	
	@Autowired
	private AppVersionService appVersionService;
	
	@Autowired
	private PushMsgService pushMsgService;
	
	@Autowired
	private InternetBarService internetBarService;
	
	@Autowired
	private RegionService regionService;
	
	@Autowired
	private WelfareActivitiesService welfareActivitiesService;
	
	@Autowired
	private PrizeService prizeService;
	
	@Autowired
	private PrizeRecordService prizeRecordService;
	
	@Autowired
	private FavoriteInternetBarService favoriteInternetBarService;
	
	@Autowired
	private BarCommentService barCommentService;
	
	@Autowired
	private InternetBarExtendService internetBarExtendService;
	
	@Autowired
	private BarInfoService barInfoService;
	
	
	public List<AppVersion> getAllAppVersion(){
		return appVersionService.getAll();
	}
	
	public void saveAppVersion(AppVersion appVersion){
		appVersionService.save(appVersion);
	}
	
	public void modifyAppVersion(AppVersion appVersion){
		appVersionService.modify(appVersion);
	}
	
	public void deleteAppVersion(int appVersionId){
		appVersionService.delById(appVersionId);
	}
	
	/*
	 * 上传文件，并返回文件大小，和文件路径
	 */
	public Map<String, String> uploadApk(String fileName){
		String apkSize = "0";     //上传文件的大小
		String apkRelativePath = "/upload/app/msg/" +  fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());    //上传文件相对路径
		logger.info("<<<<<<<<<<<< upload file target path=" + apkRelativePath);
		File file = new File(fileName);
		if(file.exists()){
			apkSize = String.valueOf(file.length());
		}
		//取得项目根据目录
		String targetPath = System.getProperty("user.dir") + "/upload/app/msg/";
		try {
			UploadUtil.upload(fileName, targetPath);
		} catch (Exception e) {
			logger.info("<<<<<<<<<<<< upload file exception", e);
			e.printStackTrace();
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("apkSize", apkSize);
		map.put("apkRelativePath", apkRelativePath);
		return map;
	}
	
	public PageInfo<PushMsg> getPushMsgByPageList(int pageNo, int pageSize){
		PageInfo<PushMsg> page = new PageInfo<PushMsg>(pageNo, pageSize);
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("type", 0);
		page.setParams(params);
		
		//将查询出的数据存入pageInfo对象中
		int total = pushMsgService.getByPageCount(page);    //总条数
		page.setTotal(total);
		page.setRows(pushMsgService.getByPageList(page));   //当前页数据
		int totalPage = page.getTotalPage(total);
		page.setTotalPage(totalPage);
		return page;
	}
	
	public void savePushmsg(PushMsg pushMsg){
		pushMsgService.save(pushMsg);
	}
	
	public PageInfo<AppBarDetail> queryAppDetail(String province, String city, String snbid, String barName, int pageNo, int pageSize) {
		PageInfo<AppBarDetail> detailPage = new PageInfo<AppBarDetail>(pageNo, pageSize);
		
		String regionIds ="";
		// 省、市条件不为空，则先从region表中查出对应网吧的regoin_id
		if (StringUtils.isNotEmpty(province)) {
			regionIds = getRegionIdStr(province, city);
		}
		
		// 根据snbid, barName从internet_bar中查询数据
		PageInfo<InternetBar> page = new PageInfo<InternetBar>(pageNo, pageSize);
		Map<String, Object> params = new HashMap<String, Object>();
		String condition = "first_login_Time>0";
		if(StringUtils.isNotEmpty(regionIds)){
			condition += " and region_id in " + regionIds;
		}
		params.put("condition", condition);
		if(StringUtils.isNotEmpty(snbid)){
			params.put("snbid", snbid);
		}
		if(StringUtils.isNotEmpty(barName)){
			params.put("barName", barName);
		}
		page.setParams(params);
		List<InternetBar> internetBarList = internetBarService.getByPageList(page);
		List<AppBarDetail> detailList = new ArrayList<AppBarDetail>();    //当前页数据
		//根据snbid查询出对应第一次订座奖励/单次订座奖励
		for(InternetBar bar : internetBarList){
			AppBarDetail detail = new AppBarDetail();
			detail.setSnbid(bar.getSnbid());
			detail.setBarName(bar.getName());
			if(StringUtils.isEmpty(city)){    //如果页面上没有输入省/市, 则从数据库中查询
				Region region = regionService.getById(bar.getRegionId());    //网吧所在地
				if(null != region){
					if(null != region.getParentRegionId()){
						Region region2 = regionService.getById(region.getParentRegionId());    //网吧父级所在地
						if(null != region2){
							if(null != region2.getParentRegionId()){
								Region region3 = regionService.getById(region2.getParentRegionId());   //网吧父父级所在地
								detail.setProvince(region3.getRegionName());
								detail.setCity(region2.getRegionName());
							}else{
								detail.setProvince(region2.getRegionName());
								detail.setCity(region.getRegionName());
							}
						}
					}else{
						detail.setProvince(region.getRegionName());
						detail.setCity(region.getRegionName());
					}
				}
			}else{
				detail.setProvince(province);
				detail.setCity(city);
			}
			detail.setTelephone(bar.getTelephone());
			String firstReward = queryRewardByInternetBarId(bar.getInternetBarId(), Byte.parseByte(2+""));  //2:首次订座
			detail.setFirstOrderReward(firstReward);
			String oneReward = queryRewardByInternetBarId(bar.getInternetBarId(), Byte.parseByte(3+""));  //2:单次订座
			detail.setOneOrderReward(oneReward);
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("internetBarId", bar.getInternetBarId());
			//查询关注用户数
			detail.setFavorite(favoriteInternetBarService.getCountByCondition(map));
			//查询吧一吧总量
			map.put("parentCommentIdIsNull", "");
			detail.setTotal(barCommentService.getCountByCondition(map));
			detail.setFirstLoginTime(FormatUtils.getTimeStr(bar.getFirstLoginTime()));
			
			detailList.add(detail);
		}
		
		int total = internetBarService.getByPageCount(page);    //总条数
		detailPage.setTotal(total);
		detailPage.setRows(detailList);   //当前页数据
		int totalPage = page.getTotalPage(total);
		detailPage.setTotalPage(totalPage);
		return detailPage;
	}
	
	public PageInfo<InternetBar> queryAppSetting(String province, String city, String snbid, String barName, int pageNo, int pageSize) {
		String regionIds ="";
		// 省、市条件不为空，则先从region表中查出对应网吧的regoin_id
		if (StringUtils.isNotEmpty(province)) {
			regionIds = getRegionIdStr(province, city);
		}
		
		// 根据snbid, barName从internet_bar中查询数据
		PageInfo<InternetBar> page = new PageInfo<InternetBar>(pageNo, pageSize);
		Map<String, Object> params = new HashMap<String, Object>();
		String condition = "(get_into_lb=1 OR open_app<>22)";
		if(StringUtils.isNotEmpty(regionIds)){
			condition += " and region_id in " + regionIds;
		}
		params.put("condition", condition);
		if(StringUtils.isNotEmpty(snbid)){
			params.put("snbid", snbid);
		}
		if(StringUtils.isNotEmpty(barName)){
			params.put("barName", barName);
		}
		page.setParams(params);
		List<InternetBar> internetBarList = internetBarService.getByPageList(page);
		
		int total = internetBarService.getByPageCount(page);    //总条数
		page.setTotal(total);
		page.setRows(internetBarList);   //当前页数据
		int totalPage = page.getTotalPage(total);
		page.setTotalPage(totalPage);
		return page;
	}
	
	public String modifyAppSetting(String snbids, int getIntoLb, int switch1, int switch2, int openAppOrder, int rechargeSwitch, int rechargeTotalSwitch){
		String exceptionInfo = "";
		String[] snbidArr = snbids.split(",");
		for(String snbid : snbidArr){
			//先查询账号在数据库中是否存在
			InternetBar barObj = new InternetBar();
			barObj.setSnbid(snbid);
			List<InternetBar> barList = internetBarService.getByPojo(barObj);
			InternetBar bar = null;
			if(null != barList && barList.size()>0){
				bar = barList.get(0);
				if (isOl(bar.getInternetBarId(), snbid) && (openAppOrder == 1 || rechargeSwitch == 1)){
					logger.info("<<<<<<<<< bar Not OL,  snbid=" + snbid);
					exceptionInfo = snbid + " not OL";
					break;
				}
			}else{
				logger.info("<<<<<<<<< bar Not Exist,  snbid=" + snbid);
				exceptionInfo = snbid + " not exist";
				break;
			}
			//如果网吧原来是没有开通充值的，修改为开通，则调用开通充值接口
			if(bar.getRechargeSwitch() == 0 && rechargeSwitch == 1){
				JSONObject result = null;
				Map<String, String> parameter = new HashMap<String, String>();
				parameter.put("snbid", snbid);
				parameter.put("from", "008-app-switch");
				result = (JSONObject)HttpClientUtil.executeHttpGet("http://qian1.sicent.com/sicentSwAccountBind.html", parameter, JSONObject.class);
				if (result == null || result.get("success") == null || result.get("success").toString().equals("false") ) {
					logger.info("<<<<<<<<< openRechargeSwitch Exception,  snbid=" + snbid);
					exceptionInfo = snbid + " open RechargeSwitch Exception";
					break;
				}
			}
			
			//将二维码总开关(switch1)/副开关(switch2)，合并到openApp值中
			String openApp = String.valueOf(switch1) + String.valueOf(switch2);
			//调用开通充值接口成功后，更新数据库信息
			bar.setRechargeTotalSwitch(rechargeTotalSwitch);
			bar.setRechargeSwitch(rechargeSwitch);
			bar.setOpenAppOrder(openAppOrder);
			bar.setOpenApp(openApp);
			bar.setGetIntoLb(getIntoLb);
			internetBarService.modify(bar);
		}
		
		return exceptionInfo;
	}
	
	public PageInfo<BarInfo> queryExamine(int status, int pageNo, int pageSize){
		//根据status从bar_info查询查询数据
		PageInfo<BarInfo> page = new PageInfo<BarInfo>(pageNo, pageSize);
		Map<String, Object> map = new HashMap<String, Object>();
		if(status == 1){
			map.put("condition", "status=1");
		}else{
			map.put("condition", "status>1");
		}
		page.setParams(map);
		List<BarInfo> barInfoList = barInfoService.getByPageList(page);
		for(BarInfo barInfo : barInfoList){
			//根据internet_bar_id查出对应snbid
			InternetBar obj = new InternetBar();
			obj.setInternetBarId(barInfo.getInternetBarId());
			List<InternetBar> barList = internetBarService.getByPojo(obj);
			if(null != barList && barList.size()>0){
				barInfo.setSnbid(barList.get(0).getSnbid());
			}
		}
		
		int total = barInfoService.getByPageCount(page);    //总条数
		page.setTotal(total);
		page.setRows(barInfoList);   //当前页数据
		int totalPage = page.getTotalPage(total);
		page.setTotalPage(totalPage);
		return page;
	}
	
	
	/*
	 * 判断账号是否是OL
	 */
	private boolean isOl(Integer internetBarId, String snbid) {
		String version = null;
		InternetBarExtend extend = new InternetBarExtend();
		extend.setInternetBarId(internetBarId);
		InternetBarExtend exBar = null;
		List<InternetBarExtend> extendList = internetBarExtendService.getByPojo(extend);
		if(null != extendList && extendList.size()>0){
			exBar = extendList.get(0);
		}
		String ver = getsVer(snbid);
		if (ver != null && ver.length() > 0){
			if (Float.valueOf(ver.substring(0, 3)) >= 4.5){
				return false;
			}else{
				return true;
			}
		}
		if (null != exBar) {
			version = exBar.getChargeVersion().toLowerCase();
		}
		if (version != null) {
			if (version.contains("ol") && Float.valueOf(version.substring(2, 5)) >= 4.5) {
				return false;
			} else {
				return true;
			}
			
		} else {
			return true;
		}
	}
	
	private String getsVer(String snbid) {
		Map<String, String> paramMap = new HashMap<String, String>();
		JSONObject source = new JSONObject();
		JSONObject parameter = new JSONObject();
		source.put("from", "qdd");
		parameter.put("snbid", snbid);
		parameter.put("dbName", "esale");
		parameter.put("flag", "SM");
		parameter.put("sql", "sicent.qdd.check.snbidinfo");
		paramMap.put("source", JSON.toJSONString(source));
		paramMap.put("parameter", JSON.toJSONString(parameter));
		JSONObject json=(JSONObject) HttpClientUtil.executeHttpGet("http://172.30.1.134:8081/cxf/http/service/data/olquery", paramMap, JSONObject.class);
		
		Map<Object, String> map = (Map<Object, String>) json.get("data");
		return map.get("sVer");
	}
	
	/*
	 * 根据省/市查询出所有的地区的regionId字符串, 格式：(1,2,3,4.......)
	 */
	private String getRegionIdStr(String province, String city){
		String regionIds = "";
		// 省、市条件不为空，则先从region表中查出对应网吧的regoin_id
		if (StringUtils.isNotEmpty(province)) {
			Region provinceRegion = new Region();
			provinceRegion.setRegionName(province);
			List<Region> provinceList = regionService.getByPojo(provinceRegion);
			if (null != provinceList && provinceList.size() > 0) {
				int provinceRegionId = provinceList.get(0).getRegionId();
				Region cityRegion = new Region();
				if (StringUtils.isEmpty(city)) { // 如果市为空, 则查出省下面所有市
					cityRegion.setParentRegionId(provinceRegionId);
				}else{    //查询指定的市
					cityRegion.setRegionName(city);
				}
				regionIds = "(";
				List<Region> cityList = regionService.getByPojo(cityRegion);
				for(Region cityRegionObj : cityList){
					int cityRegionId = cityRegionObj.getRegionId();
					regionIds += cityRegionId + ",";
					//再取得市下面的区或者县
					Region areaRegion = new Region();
					areaRegion.setParentRegionId(cityRegionId);
					List<Region> areaRegionList = regionService.getByPojo(areaRegion);
					for(Region areaRegionObj : areaRegionList){
						regionIds += areaRegionObj.getRegionId() + ",";
					}
				}
				regionIds = regionIds.substring(0, regionIds.length()-1) + ")";
				logger.info("<<<<<<<<<<< get Region by province("+ province + "), city(" + city + "), regionIds=" + regionIds);
			}
		}
		return regionIds;
	}
	
	/*
	 * 查询订座
	 * type=2: 第一次订座, 3: 单次订座
	 */
	private String queryRewardByInternetBarId(int internetBarId, byte type){
		String reward = "";
		WelfareActivities wa = new WelfareActivities();
		wa.setInternetBarId(internetBarId);
		wa.setType(type);
		List<WelfareActivities> WelfareActivitiesList = welfareActivitiesService.getByPojo(wa);
		if(null != WelfareActivitiesList && WelfareActivitiesList.size()>0){
			WelfareActivities waObj = WelfareActivitiesList.get(0);
			//从prize表中取出对应的奖励
			Prize prize = new Prize();
			prize.setWelfareActivitiesId(waObj.getWelfareActivityId());
			List<Prize> prizeList = prizeService.getByPojo(prize);
			if(null != prizeList && prizeList.size()>0){
				Prize prizeObj = prizeList.get(0);
				reward = prizeObj.getName();
				int prizeType = prizeObj.getType();
				if(reward.contains("#|#")){
					reward = reward.split("#|#")[1] + " " + reward.split("#|#")[0];
				}
				if(prizeType == 1){
					reward += "元网费";
				}else if(prizeType == 3){
					reward += "元代金券";
				}
				//取对应奖励的人数
				int num = queryRewardNumByInternetBarId(internetBarId, waObj.getWelfareActivityId(), prizeObj.getPrizeId());
				reward += "/" + num; 
			}
		}
		return reward;
	}
	
	/*
	 * 查询首次订座/单次订座的人数
	 */
	private int queryRewardNumByInternetBarId(int internetBarId, int welfareActivityId, int prizeId){
		int num = 0;   //获奖人数
		PrizeRecord record = new PrizeRecord();
		record.setInternetBarId(internetBarId);
		record.setWelfareActivityId(welfareActivityId);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("internetBarId", internetBarId);
		map.put("welfareActivityId", welfareActivityId);
		map.put("prizeId", prizeId);
		num = prizeRecordService.getCountByCondition(map);
		return num;
	}
	
}
